#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Predesys Server - Core - System
@version: 0.2.5
@license: GPL 3.0 (see "license" file)
@author: Jose A. Jimenez
@contact: jajimc@gmail.com"""

import sys
sys.dont_write_bytecode = True
import os
import os.path
DIR = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(os.path.join(DIR, "../errorlog"))
import errorlog
sys.path.append(os.path.join(DIR, "../data"))
import security
import coreexceptions
import configuration
import data

def get_core_path():
    """Gets Predesys Server Core directory path.
    @return: Core path
    @rtype: C{str}"""
    return DIR
    
def install_db():
    """Installs Predesys Server data base. Predesys Server must be previously configured."""
    security.check_root()
    
    config = configuration.load_configuration()
    dbType = config.get_db_type()

    if dbType == None or dbType == "":
        errorlog.log_exception(Exception("Data base settings not set"), "predesys-server.core.system.install_db")
        raise coreexceptions.DataBaseException("Data base settings not set")
    
    sqlFile = os.path.join("../data", "predesys-server-data-%s.sql" % dbType)
    
    try:
        f = open(sqlFile, "r")
        dbSql = f.read()
    except Exception as exc:
        errorlog.log_exception(exc.args[0], "predesys-server.core.system.install_db")
        raise Exception("Error loading DB SQL file")
        
    try:
        dbConnection = data.open_connection()
        result = data.execute(dbConnection, dbSql)
        result.close()        
        data.close_connection(dbConnection)
    except Exception as exc:
        errorlog.log_exception(exc.args[0], "predesys-server.core.system.install_db")
        raise Exception("DB error")
